﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace SqlMidasala
{
    class Validate
    {
        /// <summary>
        /// Validates an icelandic id number
        /// </summary>
        /// <param name="id">Icelandic id number also known as kennitala</param>
        /// <returns></returns>
        public bool IsValidID(string id) // DDMMYY-NNCZ
        {
            int c = -1; // skilagildi
            uint dump; // tmp um hald til að athuga ef id er 
            string o = "";
            bool output = false;
            if (id.Length >= 10)
            {
                if (UInt32.TryParse(id, out dump))
                    o = id.ToString();
                else if (id.Length >= 10)
                    for (int i = 0; i < id.Length; i++)
                        if (char.IsDigit(id[i]))
                            o += id[i];
                if (o.Length >= 10)
                    c = GetC(o);
                if (o.Length == 10 || o[8].ToString() == c.ToString())
                    output = true;
            }
            return output;
        }

        // see if the next to last number in id is valid
        /// <summary>
        /// Formula for the next to last numver in an icelandic id number(kennitala)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        private int GetC(string id)
        {
            int[] k = new int[8]; // fyrstu átta stafirnir í kennitölu í int
            int[] m = { 3, 2, 7, 6, 5, 4, 3, 2 }; // lykill
            int sum = 0; // summa
            int c; // skila gildi

            // færir strengin í k[]
            for (int i = 0; i < k.Length; i++)
                k[i] = int.Parse(id[i].ToString());
            
            // reiknar summu margfölduninar
            for (int i = 0; i < k.Length; i++)
                sum += k[i] * m[i];

            c = 11 - (sum % 11);
            // ef c er ekki 11 skila á c ef c er 11 skila 0
            return (c != 11) ? c : 0;
        }

        /// <summary>
        /// Regex email validation
        /// </summary>
        /// <param name="email">Email address</param>
        /// <returns></returns>
        public bool IsValidEmail(string email)
        {
            bool o = false;
            Regex regexEmail = new Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");
            if (regexEmail.IsMatch(email))
                o = true;
            return o;
        }
    }
}
